<template>
  <div>
    <div class="header">
      <button @click="prevMonth">&lt;</button>
      <h2>{{ month }}月{{ year }}年</h2>
      <button @click="nextMonth">&gt;</button>
    </div>
    <table>
      <thead>
        <tr>
          <th v-for="day in days">{{ day }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="week in weeks">
          <td v-for="day in week" :class="{ today: isToday(day), selected: isSelected(day) }" @click="selectDate(day)">
            {{ day.getDate() }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1,
      days: ['日', '一', '二', '三', '四', '五', '六'],
      selectedDate: null
    }
  },
  computed: {
    weeks() {
      const firstDayOfMonth = new Date(this.year, this.month - 1, 1)
      const lastDayOfMonth = new Date(this.year, this.month, 0)
      const firstDayOfCalendar = new Date(firstDayOfMonth)
      firstDayOfCalendar.setDate(firstDayOfCalendar.getDate() - firstDayOfCalendar.getDay())
      const lastDayOfCalendar = new Date(lastDayOfMonth)
      lastDayOfCalendar.setDate(lastDayOfCalendar.getDate() + (6 - lastDayOfCalendar.getDay()))
      const weeks = []
      let currentDay = new Date(firstDayOfCalendar)
      while (currentDay <= lastDayOfCalendar) {
        const week = []
        for (let i = 0; i < 7; i++) {
          week.push(new Date(currentDay))
          currentDay.setDate(currentDay.getDate() + 1)
        }
        weeks.push(week)
      }
      return weeks
    }
  },
  methods: {
    isToday(date) {
      const today = new Date()
      return date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate()
    },
    isSelected(date) {
      return this.selectedDate && date.getFullYear() === this.selectedDate.getFullYear() && date.getMonth() === this.selectedDate.getMonth() && date.getDate() === this.selectedDate.getDate()
    },
    selectDate(date) {
      this.selectedDate = date
    },
    prevMonth() {
      if (this.month === 1) {
        this.year--
        this.month = 12
      } else {
        this.month--
      }
    },
    nextMonth() {
      if (this.month === 12) {
        this.year++
        this.month = 1
      } else {
        this.month++
      }
    }
  }
}
</script>

<style>
table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}

.today {
  background-color: #eee;
}

.selected {
  background-color: #ccc;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.header button {
  background-color: transparent;
  border: none;
  font-size: 24px;
  cursor: pointer;
}
</style>